package com.juku2024.juku

import android.os.Bundle
import android.text.TextUtils
import android.view.View
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.juku2024.juku.adapter.HistoryAdapter
import com.juku2024.juku.base.BaseActivity
import com.juku2024.juku.db.NoteRoomUtils
import com.juku2024.juku.db.entity.HistoryEntity
import com.juku2024.juku.model.CommonModel
import com.juku2024.juku.tools.AppUtils
import com.juku2024.juku.viewmodel.MainViewModel
import com.juku2024.juku.widget.HeaderView
import com.juku2024.juku.widget.LoadingView

class WatchingActivity: BaseActivity(), View.OnClickListener {

    private lateinit var header: HeaderView
    private lateinit var deleteTv: TextView
    private lateinit var selectAllTv: TextView
    private lateinit var bottomInfoLl: View
    private lateinit var loadingView: LoadingView
    private lateinit var watchingRecycler: RecyclerView
    private val adapter by lazy { HistoryAdapter(ArrayList()) }
    private val viewModel by lazy { getViewModel(MainViewModel::class.java) }

    override fun getLayoutResId(): Int {
        return R.layout.activity_watching_list
    }

    override fun initView() {
        super.initView()
        header = findViewById(R.id.header)
        deleteTv = findViewById(R.id.deleteTv_watching_list)
        selectAllTv = findViewById(R.id.selectAllTv_watching_list)
        bottomInfoLl = findViewById(R.id.bottomInfoLl_watching_list)
        loadingView = findViewById(R.id.loadingView_watching_list)
        watchingRecycler = findViewById(R.id.watchingRecycler)


        watchingRecycler.layoutManager = LinearLayoutManager(this)
        watchingRecycler.setHasFixedSize(true)
        watchingRecycler.adapter = adapter
    }

    override fun bindEvent() {
        super.bindEvent()
        header.setOnEditClickListener(this)
        deleteTv.setOnClickListener(this)
        selectAllTv.setOnClickListener(this)


        adapter.setOnItemChildClickListener { _, _, position ->
            checkSelectState(adapter.data[position])
            adapter.notifyItemChanged(position)
        }
        adapter.setOnItemClickListener { _, _, position ->
            checkSelectState(adapter.data[position])
            adapter.notifyItemChanged(position)
            if (bottomInfoLl.visibility != View.VISIBLE) {
                VideoDetailActivity.toVideoDetail(this, adapter.data[position].videoId, adapter.data[position].name)
            }
        }
    }
    @Suppress("DEPRECATION")
    @Deprecated("Deprecated in Java")
    override fun init(savedInstanceState: Bundle?) {
        val watchingList = intent?.getParcelableArrayListExtra<CommonModel>("watching") as ArrayList<CommonModel>?
        if (watchingList == null) {
            loadingView.showLoading()
            doHttpVideoUpdateCheck()
        } else {
            adapter.setList(format(watchingList))
        }
    }

    private fun doHttpVideoUpdateCheck() {
        // 查询追剧片单
        viewModel.checkVideoUpdate({ list ->
            if (isActivityNotActive()) return@checkVideoUpdate
            loadingView.hideLoading()
            // 必须在请求列表完成后
            adapter.setList(format(list))
        }, {
            if (isActivityNotActive()) return@checkVideoUpdate
            loadingView.hideLoading()
            loadingView.showEmptyStatus("您还尚未进行追剧！")
        })
    }

    private fun format(list: ArrayList<CommonModel>): ArrayList<HistoryEntity>{
        val target = ArrayList<HistoryEntity>()
        list.forEach {
            var entity = NoteRoomUtils.getInstance().historyDao().queryHistory(it.id)
            if (entity == null) {
                entity = HistoryEntity()
            }

            val episode = it.theLastEpisode?:0
            entity.isNewEpisode = it.isWatching && episode > 0

            target.add(entity)
        }

        return target
    }

    override fun onClick(p0: View?) {
        when (p0!!) {
            selectAllTv -> selectOrCancelAll()
            deleteTv -> delete()
            else -> clickEdit()
        }
    }
    private fun checkSelectState(item: HistoryEntity) {
        item.isSelect = !item.isSelect
        var nums = 0
        adapter.data.forEach {
            if (it.isSelect) {
                nums++
            }
        }
        if (nums >= adapter.data.size) {
            selectAllTv.text = AppUtils.getString(R.string.cancel_select_all)
            deleteTv.text = String.format(AppUtils.getString(R.string.delete_num), nums)
            deleteTv.setTextColor(AppUtils.getColor(R.color.color_text_light))
        } else {
            if (nums > 0) {
                deleteTv.text = String.format(AppUtils.getString(R.string.delete_num), nums)
                deleteTv.setTextColor(AppUtils.getColor(R.color.color_text_light))
            } else {
                deleteTv.text = AppUtils.getString(R.string.delete)
                deleteTv.setTextColor(AppUtils.getColor(R.color.color_text_dark))
            }
            selectAllTv.text = AppUtils.getString(R.string.select_all)
        }
    }


    private fun delete() {
        showErrorDialog(
            "您确认删除选中的内容吗？",
            getString(R.string.confirm), {
                hideErrorDialog()
                val currentList = adapter.data.filter { it.isSelect }
                adapter.data.removeAll(currentList)

                currentList.forEach {
                    NoteRoomUtils.getInstance().videoUpdateDao().delete(it.videoId)
                }
                adapter.notifyDataSetChanged()
                val count = adapter.data.count { it.isSelect }
                deleteTv.text = String.format(AppUtils.getString(R.string.delete_num), count)

                if (adapter.data.isEmpty()) {
                    bottomInfoLl.visibility = View.GONE
                    header.setMenuText(getString(R.string.edit))
                    loadingView.showEmptyStatus("暂无追剧片单！")
                }
            }, getString(R.string.cancel), {
                hideErrorDialog()
            }
        )
    }

    private fun selectOrCancelAll() {
        if (selectAllTv.text == AppUtils.getString(R.string.select_all)) {
            selectAllTv.text = AppUtils.getString(R.string.cancel_select_all)
            deleteTv.text =
                String.format(AppUtils.getString(R.string.delete_num), adapter.data.size)
            deleteTv.setTextColor(AppUtils.getColor(R.color.color_text_light))
            adapter.data.forEach {
                it.isSelect = true
            }
        } else {
            deleteTv.text = AppUtils.getString(R.string.delete)
            deleteTv.setTextColor(AppUtils.getColor(R.color.color_text_dark))
            selectAllTv.text = AppUtils.getString(R.string.select_all)
            adapter.data.forEach {
                it.isSelect = false
            }
        }
        adapter.notifyDataSetChanged()
    }

    private fun clickEdit() {
        if (adapter.data.size == 0) {
            return
        }
        adapter.isEditStatus = !(adapter.isEditStatus)
        adapter.data.forEach {
            it.isSelect = false
        }

        selectAllTv.text = AppUtils.getString(R.string.select_all)
        deleteTv.text = AppUtils.getString(R.string.delete)
        deleteTv.setTextColor(AppUtils.getColor(R.color.color_text_dark))
        adapter.notifyDataSetChanged()

        val text = if (adapter.isEditStatus) {
            bottomInfoLl.visibility = View.VISIBLE
            AppUtils.getString(R.string.cancel)
        } else {
            bottomInfoLl.visibility = View.GONE
            AppUtils.getString(R.string.edit)
        }
        if (!TextUtils.isEmpty(text)) {
            header.setMenuText(text)
        }
    }

    @Suppress("DEPRECATION")
    @Deprecated("Deprecated in Java")
    override fun onBackPressed() {
        if (adapter.isEditStatus) {
            adapter.isEditStatus = false
            adapter.notifyDataSetChanged()
            bottomInfoLl.visibility = View.GONE
            header.setMenuText(AppUtils.getString(R.string.edit))
            return
        }
        super.onBackPressed()
    }
}